from django.shortcuts import render
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from apps.oauth.utility import changepassword, restorepassword
from apps.oauth.models import OAuthQQUser
from django.contrib.auth import login
from django_redis import get_redis_connection
import json, re
from apps.users.models import User


# Create your views here.
class QQUrlView(View):
    """
    用于QQ登录接口
    """

    def get(self, request):
        """
        处理用户QQ登录
        :param request:# GET http: // www.meiduo.site: 8000 / qq / authorization /?next = /
        :return:
        """
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()
        # print(login_url)

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': login_url})


class QQInfoView(View):
    """
    用于扫码授权后获取QQ隐私信息
    """

    def get(self, request):
        """
        获取QQ隐私信息
        :param request:
        :return:
        """
        code = request.GET.get('code')
        if not code:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必须参数', })

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, )

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': 'oauth2.0认证失败', })

        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 未绑定的QQ用户
            access_token = changepassword(openid)
            return http.JsonResponse({'code': 300, 'errmsg': 'ok', 'access_token': access_token})
        else:
            # 绑定的QQ用户
            user = oauth_qq.user

            login(request, user)
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username', user.username, None)
            return response

    def post(self, request):

        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        sms_code_cline = json_dict.get('sms_code')
        access_token = json_dict.get('access_token')

        if not all([mobile, password, sms_code_cline, access_token]):
            return http.JsonResponse({'code': 300, 'errmsg': '缺少必须参数'})

        # 判断用户名格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': '400', 'errmsg': '手机号有误'})

        # 判断密码格式
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': '400', 'errmsg': '密码格式有误'})

        # 判断短信验证码是否一致
        redit_conn = get_redis_connection('verify_code')
        # 根据手机号获取数据库的短信验证码sms_code
        sms_code_server = redit_conn.get('sms_code_ %s' % mobile)
        # 如果 not null
        if not sms_code_server:
            return http.JsonResponse({'code': '300', 'errmsg': '短信验证码已失效'})

        # 如果存在就比较请求数据里面的sms_code是否和数据库的相等
        if sms_code_cline != sms_code_server.decode():
            return http.JsonResponse({'code': '300', 'errmsg': '短信验证码错误'})

        # 解密openid
        openid = restorepassword(access_token)

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在的情况
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)

        else:
            # 手机号存在的情况
            # 判断密码是否相等
            if User.check_password(password):
                return http.JsonResponse({'code': 400, 'errmsg': '手机号或密码错误'})
        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:

            return http.JsonResponse({'code': 400, 'errmsg': 'QQ登录失败'})
        login(request, user)

        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=None)

        return response

    #
    # try:
    #     user = User.objects.get(mobile=mobile)
    #
    # except OAuthQQUser.DoesNotExist:
    #     # 手机号不存在建立用户
    #     user = User.objects.create_user(username=mobile, password=password, mobile=mobile)
    # else:
    #     # 手机号存在，判断密码
    #     if not User.check_password(password):
    #         return http.JsonResponse({'code': '300', 'error_message': '手机号或密码错误'})
    #
    # try:
    #     openid = restorepassword(access_token)
    #     OAuthQQUser.objects.create(openid=openid, user=user)
    # except DatabaseError:
    #     return http.JsonResponse({'code': 300, 'error_message': '数据添加数据出错'})
    #
    # login(request, user)
    #
    # response = http.JsonResponse({'code': 0, 'error_message': 'ok'})
    # response.set_cookie('username', user.username, max_age=None)
    #
    # return response
